const app = getApp();
const gbToBase64 = require("../../utils/gb2312ToBase64.js");
const cpcl = require('../../utils/cpcl.js');
const tspl = require('../../utils/tspl.js');
const esc = require('../../utils/esc.js');

export default {
	data() {
		return {
			cpcl: 'CPCL-三寸便携(QR386)',
			tspl: 'TSPL-四寸桌面(QR488/588)',
			esc: 'ESC-两寸便携',
			cpclIndex: '0',
			tsplIndex: '1',
			escIndex: '2',

			currentDevName: 'defaulName',
			currentConnectionState: '已连接',

			recvTotalBytes: '0',

			recv_data: '',
			scrollTop: 0,
			send_data: '',

			devId: '',
			services: [],
			connected: false,

			notifyServiceId: 'invalid',
			notifyCharacteristicId: 'invalid',
			notifyServiceSearchIndex: 0,

			writeServiceId: 'invalid',
			writeCharacteristicId: 'invalid',
			writeServiceSearchIndex: 0
		}
	},
	onLoad: function(options) {
		var btDevId = options.devId;
		var that = this;

		var num = that.services.length
		that.services.splice(0, num)

		for (var i = 0; i < app.globalData.btDevices.length; ++i) {
			if (app.globalData.btDevices[i].devId == btDevId) {
				console.log('!!!createBLEConnection', btDevId)
				that.currentDevName = app.globalData.btDevices[i].name;
				that.currentConnectionState = '连接中...';
				uni.createBLEConnection({ // 连接低功耗蓝牙设备
					// 这里的 btDevId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
					deviceId: app.globalData.btDevices[i].devId,
					success: function(res) {
						setTimeout(() => {
							console.log(res)
							that.devId = btDevId
							uni.getBLEDeviceServices({ // 获取蓝牙设备所有服务
								// 这里的 devId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
								deviceId: that.devId,
								success: function(res) {
									console.log('device services:', res.services)
									// 保存已连接设备的服务
									for (var j = 0; j < res.services.length; ++j) {
										var newService = [
											res.services[j],
										]
										that.services = that.services.concat(newService)
										console.log(j, that.services.length, res.services.length)
									}

									// 寻找第一个Notify特征
									that.notifyServiceSearchIndex = 0
									that.notifyCharacteristicId = 'invalid'
									that.seekFirstNotifyCharacteristic()
								}
							})
						}, 1500)
					}
				})
				break;
			}
		}
	},
	onShow: function() {
		var that = this;

		uni.onBLECharacteristicValueChange(function(res) {
			var lang = that.recv_data;
			if (String.fromCharCode.apply(null, new Uint8Array(res.value)) == 'OK') {
				uni.showToast({
					title: '打印成功',
					icon: 'success',
					duration: 2000
				})
			}

			console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`)
			console.log(String.fromCharCode.apply(null, new Uint8Array(res.value)))
			lang += String.fromCharCode.apply(null, new Uint8Array(res.value))
			that.recvTotalBytes = lang.length.toString();
			that.recv_data = lang;
			// that.scrollTop=that.scrollTop + 20;
		})

		uni.onBLEConnectionStateChange(function(res) {
			console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
		})

		uni.onBluetoothAdapterStateChange(function(res) {
			console.log(`adapterState changed, now is`, res)
		})
	},

	onUnload: function() {
		var that = this;
		uni.closeBLEConnection({
			deviceId: that.devId,
			success: function(res) {
				console.log(res)
			}
		})
	},

	methods: {
		bindButtonClearAll: function() {
			var that = this;
			console.log('clearAll')
			that.recv_data = '';
			that.recvTotalBytes = '0';
		},

		seekFirstNotifyCharacteristic: function() {
			var that = this;
			if (that.notifyServiceSearchIndex < that.services.length && that.notifyCharacteristicId == 'invalid') {
				that.notifyServiceId = that.services[that.notifyServiceSearchIndex].uuid
				console.log('Search service index ', that.notifyServiceSearchIndex, 'service: ', that.notifyServiceId)
					++that.notifyServiceSearchIndex;
				uni.getBLEDeviceCharacteristics({
					// 这里的 devId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
					deviceId: that.devId,
					// 这里的 notifyServiceId 需要在 getBLEDeviceServices 接口中获取
					serviceId: that.notifyServiceId,
					complete: function() {
						console.log('device getBLEDeviceCharacteristics complete', that.notifyServiceSearchIndex)
						//递归调用自身直到找到notify特征或遍历完所有特征
						that.seekFirstNotifyCharacteristic()
					},
					success: function(res) {
						console.log('device getBLEDeviceCharacteristics:', res.characteristics)
						for (var n = 0; n < res.characteristics.length && that.notifyCharacteristicId == 'invalid'; ++n) {
							if (res.characteristics[n].properties.notify == true) {
								console.log('device notify Characteristics found', n)
								that.notifyCharacteristicId = res.characteristics[n].uuid
								console.log('notify servcie:', that.notifyServiceId)
								console.log('notify characteristic:', that.notifyCharacteristicId)
								console.log('start notify')
								uni.notifyBLECharacteristicValueChange({
									state: true, // 启用 notify 功能
									// 这里的 devId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
									deviceId: that.devId,
									// 这里的 notifyServiceId 需要在 getBLEDeviceServices 接口中获取
									serviceId: that.notifyServiceId,
									// 这里的 notifyCharacteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
									characteristicId: that.notifyCharacteristicId,
									success: function(res) {
										console.log('notifyBLECharacteristicValueChange success', res.errMsg)
										uni.showToast({
											title: '连接成功',
											icon: 'success',
											duration: 2000
										})
										that.currentConnectionState = '已连接';
										that.connected = true

										// 寻找第一个write特征
										that.writeServiceSearchIndex = 0
										that.writeCharacteristicId = 'invalid'
										that.seekFirstWriteCharacteristic()
									}
								})
							}
						}
					}
				})
			}
		},

		seekFirstWriteCharacteristic: function() {
			var that = this;

			if (that.writeServiceSearchIndex < that.services.length && that.writeCharacteristicId == 'invalid') {
				that.writeServiceId = that.services[that.writeServiceSearchIndex].uuid
				console.log('Search service index ', that.writeServiceSearchIndex, 'service: ', that.writeServiceId)
					++that.writeServiceSearchIndex;
				uni.getBLEDeviceCharacteristics({
					// 这里的 devId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
					deviceId: that.devId,
					// 这里的 writeServiceId 需要在 getBLEDeviceServices 接口中获取
					serviceId: that.writeServiceId,
					complete: function() {
						console.log('device getBLEDeviceCharacteristics complete', that.writeServiceSearchIndex)
						//递归调用自身直到找到write特征或遍历完所有特征
						that.seekFirstWriteCharacteristic()
					},
					success: function(res) {
						console.log('device getBLEDeviceCharacteristics:', res.characteristics)
						for (var n = 0; n < res.characteristics.length && that.writeCharacteristicId == 'invalid'; ++n) {
							if (res.characteristics[n].properties.write == true) {
								console.log('device write Characteristics found', n)
								that.writeCharacteristicId = res.characteristics[n].uuid
								console.log('write servcie:', that.writeServiceId)
								console.log('write characteristic:', that.writeCharacteristicId)
							}
						}
					}
				})
			}
		},

		//测试打印
		printBtn: function(index) {
			var that = this;
			var sendData = '';
			var arrayBuffer = '';
			var base64Str = '';
			var index = index;
			console.log('the index is', index);
			if (that.connected) {
				switch (index) {
					case '0':
						sendData = cpcl.val;
						base64Str = gbToBase64.encode64(sendData)
						arrayBuffer = uni.base64ToArrayBuffer(base64Str);
						break;
					case '1':
						sendData = tspl.val;
						base64Str = gbToBase64.encode64(sendData)
						arrayBuffer = uni.base64ToArrayBuffer(base64Str);
						break;
					case '2':
						sendData = esc.val;
						arrayBuffer = gbToBase64.string2HexArrayBuffer(sendData)
						break;
				};
				uni.showToast({
					title: '发送中...',
					mask: true,
					icon: 'loading',
					duration: 2000000
				})
				if (app.globalData.platform == 'ios') {
					uni.writeBLECharacteristicValue({
						// 这里的 devId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
						deviceId: that.devId,
						// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
						serviceId: that.writeServiceId,
						// 这里的 writeCharacteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
						characteristicId: that.writeCharacteristicId,
						// 这里的value是ArrayBuffer类型
						value: arrayBuffer,
						success: function(res) {
							uni.showToast({
								title: '发送成功',
								icon: 'success',
								duration: 2000
							})
							console.log('writeBLECharacteristicValue success', res.errMsg)
						},
						fail: function(res) {
							console.log('writeBLECharacteristicValue fail', res.errMsg)
						}
					})
				} else {
					let dataView1 = new DataView(arrayBuffer)
					var length = dataView1.byteLength
					var size = 100
					var package_count = Math.round(length / size + 0.5);
					this.writeFuction(that, arrayBuffer, package_count, size);
				}
			} else {
				uni.showToast({
					title: '打印机未连接',
					icon: 'fail',
					duration: 2000
				})
			}
		},

		writeFuction: function(that, data, count, size) {
			let dataView_temp1 = new DataView(data);
			var packages = Math.round(dataView_temp1.byteLength / size + 0.5)
			var yushu = dataView_temp1.byteLength % size
			let buffer = null
			let dataView_temp2 = null
			if (yushu != 0 && count == 1) {
				buffer = new ArrayBuffer(yushu)
				dataView_temp2 = new DataView(buffer)
				for (var i = 0; i < dataView_temp2.byteLength; i++) {
					dataView_temp2.setUint8(i, dataView_temp1.getUint8((packages - count) * size + i))
				}
			} else {
				buffer = new ArrayBuffer(size)
				dataView_temp2 = new DataView(buffer)
				for (var i = 0; i < dataView_temp2.byteLength; i++) {
					dataView_temp2.setUint8(i, dataView_temp1.getUint8((packages - count) * size + i))
				}
			}
			uni.writeBLECharacteristicValue({
				// 这里的 devId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
				deviceId: that.devId,
				// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
				serviceId: that.writeServiceId,
				// 这里的 writeCharacteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
				characteristicId: that.writeCharacteristicId,
				// 这里的value是ArrayBuffer类型
				value: buffer,
				// value: arrayBuffer,
				success: function(res) {
					if (count != 0) {
						setTimeout(() => {
							that.writeFuction(that, data, count, size)
						}, 500)
					} else {
						uni.showToast({
							title: '发送成功',
							icon: 'success',
							duration: 2000
						})
					}
				},
				fail: function() {
					uni.showToast({
						title: '发送失败',
						icon: 'fail'
					})
				},
				complete: function(res) {
					console.log(res);
				}
			})
			count--;
			return 0;

		}
	}
}
